package cc.idoone.spring_boot_hello.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author hemj
 * @since 2017/10/21
 */
public class ShiroRealm extends AuthorizingRealm {

	// 权限配置实现
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("MyShiroRealm.doGetAuthorizationInfo()");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal();
		if ("root".equals(userInfo.getUsername())) {
			// 配置角色
			authorizationInfo.addRole("root");
			authorizationInfo.addRole("admin");
			// 配置权限
			authorizationInfo.addStringPermission("sys.user.getUser");
			authorizationInfo.addStringPermission("sys.user.addUser");
			authorizationInfo.addStringPermission("sys.user:userDel");
			return authorizationInfo;
		} else {
			authorizationInfo.addRole("admin");
			authorizationInfo.addStringPermission("sys.user.getUser");
			authorizationInfo.addStringPermission("sys.user.addUser");
		}

		// 建议添加缓存处理
		return authorizationInfo;
	}

	// 登录认证实现
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
		// 获取用户的输入的账号.
		String username = (String) token.getPrincipal();
		System.out.println(token.getCredentials());

		// 从数据库中查找用户
		UserInfo userInfo;

		if ("root".equals(username)) {
			userInfo = new UserInfo("root", "123456", "123");
			PasswordHelper.encrypt(userInfo);
		} else if ("admin".equals(username)) {
			userInfo = new UserInfo("admin", "123456", "123");
			PasswordHelper.encrypt(userInfo);
		} else {
			return null;
		}

		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				userInfo, // 用户信息
				userInfo.getPassword(), // 密码
				ByteSource.Util.bytes(userInfo.getCredentialsSalt()),
				getName()  // realm name
		);
		return authenticationInfo;
	}
}
